using System;
using Science.Mathematics;
using L=Science.Physics.GeneralPhysics;

namespace Serway.Chapter23
{
	/// <summary>
	/// Example04: Find the Charge on the Spheres
	/// Two identical small charged spheres, each having
	/// a mass of 3.0 \times 10^{-2} kg, hang in equilibrium
	/// as shown in Figure. The length of each string is 0.15 m,
	/// and the angle \theta is 5^{\circle}. Find the magnitude
	/// of the charge on each sphere.
	/// q = 4.4 \times 10^{-8} C	
	/// </summary>
	public class Example04
	{
		public Example04()
		{
		}
		private string result;
		public string Result
		{
			get{return result;}
		}
		public void Compute()
		{
			Function.DoubleAToDouble f 
				= new Function.DoubleAToDouble(func);
			Science.Mathematics.Calculus.Minimization obj = new Science.Mathematics.Calculus.Minimization(f);
			obj.NumberOfVariables = 2;
			double[] x = {-4.0E-5,0.0};  // one-dim did not work.
			obj.CenterOfInitialSimplex = x;
			obj.SizeOfInitialSimplex = 1.0E-5;
			obj.Compute();  
			result+=Convert.ToString(obj.MinimumAT[0])+"\r\n";
			result+=Convert.ToString(obj.MinimumValue)+"\r\n";
		}

		private double func(double[] x)
		{
			L.ElectricCharge q = new L.ElectricCharge();
			q.C = x[0];
			L.Mass m = new L.Mass();
			m.kg = 3.0*0.01;
			L.Length l = new L.Length();
			l.m = 0.15;
			L.Position r1 = new L.Position();
			r1.X = -l.m*Math.Sin(5.0*Math.PI/180.0);
			L.Position r2 = new L.Position();
			r2.X = l.m*Math.Sin(5.0*Math.PI/180.0);
            
			L.ElectricForce F = new L.ElectricForce(q,r1,q,r2);
			double zero = Math.Tan(5.0*Math.PI/180.0) - F.N / m.kg / L.Constant.AccelerationOfGravity;
			return zero*zero + x[1]*x[1];
		}
	}
}
